#import "TouchableWindow.h"

/**
 * A TouchableWindow is a window that is touchable and delegates
 * events to any subviews it contains
 * 
 * @author      James Lin
 * @version     2.3.0
 * @since       1.0.0
 */
@implementation TouchableWindow

/**
 * Initialize the touchable window.
 *
 * @param theView       the main view from which to intercept touch events
 * @param theDelegates  the delegates handling touchable window events
 * @return              the initialized TouchableWindow
 */
- (id)initWithView:(UIView*)theView 
		 delegates:(NSArray*)theDelegates {
    if (self = [super initWithFrame:[[UIScreen mainScreen] bounds]]) {
        mainView = theView;
		firstDelegate = [theDelegates objectAtIndex:0];
		secDelegate = [theDelegates objectAtIndex:1];
    }
    return self;
}

/**
 * Pass down notification of a touch event.
 */
- (void)sendEvent:(UIEvent*)event {
	[super sendEvent:event];
	NSSet* touches = [event allTouches];
	
	if (touches.count != 1) {
		return;
	}
	
	UITouch* touch = touches.anyObject;
	if (touch.phase != UITouchPhaseEnded) {
		return;
	}
	if ([touch.view isDescendantOfView:mainView] == NO) {
		return;
	}
	
	CGPoint touchPoint = [touch locationInView:mainView];
	
	[firstDelegate touchedAtPoint:touchPoint];
	[secDelegate touchedAtPoint:touchPoint];
}

/**
 * Deallocate the touchable window.
 */
- (void)dealloc {
	mainView = nil;
	firstDelegate = nil;
	secDelegate = nil;
    [super dealloc];
}

@end
